<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="合同审核列表"
      rowKey="id"
      :columns="columns"
      :requestApi="ContractApi.page"
      :dataCallback="dataCallback"
      :initParam="initParam"
      :searchCol="{ xs: 2, sm: 3, md: 4, lg: 6, xl: 8 }"
    >
      <!-- 表格 header 按钮 -->
      <!-- <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" v-hasPermi="['sys:contract:add']" @click="openDrawer('新增')">新增商品</el-button>
        <el-button type="success" :icon="Printer" v-hasPermi="['sys:contract:print']" @click="batchPrint">批量打印</el-button>
      </template> -->
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="success" link :icon="CircleCheckFilled" v-hasPermi="['sys:contract:pass']" @click="approvalContract(scope.row, 0)">审核通过</el-button>
        <el-button type="danger" link :icon="CircleCloseFilled" v-hasPermi="['sys:contract:reject']" @click="approvalContract(scope.row, 1)">审核不通过</el-button>
      </template>
    </ProTable>
    <!-- 审核对话框 -->
    <el-dialog v-model="approvalDialogVisible" :title="approvalTitle" width="500px" :before-close="handleDialogClose">
      <el-form :model="approvalForm" label-width="80px">
        <el-form-item label="合同名称">
          <el-input v-model="currentContract.name" disabled />
        </el-form-item>
        <el-form-item label="合同编号">
          <el-input v-model="currentContract.number" disabled />
        </el-form-item>
        <el-form-item label="审核意见" required>
          <el-input v-model="approvalForm.comment" type="textarea" :rows="4" :placeholder="approvalPlaceholder" maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitApproval" :loading="approvalLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ContractManage">
import { ref, reactive, computed } from 'vue'
import { ColumnProps } from '@/components/ProTable/interface'
import ProTable from '@/components/ProTable/index.vue'
import { ContractApi } from '@/api/modules/contract/index'
import { ContractStatusList } from '@/configs/enum'
import { CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import { useHandleData } from '@/hooks/useHandleData'
import { ElMessage } from 'element-plus'

// 表格配置项
const columns: ColumnProps[] = [
  { type: 'selection', fixed: 'left', width: 60 },
  {
    prop: 'name',
    label: '合同名称',
    search: { el: 'input' },
    minWidth: 150
  },
  {
    prop: 'number',
    label: '合同编号',
    minWidth: 120,
    search: { el: 'input' }
  },
  {
    prop: 'customerName',
    label: '客户姓名',
    minWidth: 120,
    search: { el: 'input' }
  },
  {
    prop: 'amount',
    label: '合同金额',
    minWidth: 100
  },
  {
    prop: 'receivedAmount',
    label: '已收到款项',
    minWidth: 100
  },
  {
    prop: 'status',
    label: '合同状态',
    enum: Object.values(ContractStatusList),
    search: { el: 'select' },
    tag: true,
    minWidth: 120
  },
  {
    prop: 'signTime',
    label: '签约时间',
    minWidth: 100
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 200 }
]
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref()

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ status: 1 })
// 处理返回数据格式
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  }
}

//合同审核
const approvalContract = async (row: any, type: number) => {
  //   await useHandleData(ContractApi.approvalContract, { id: row.id, type }, type === 0 ? '合同审核通过' : '合同审核不通过')
  //   proTable.value.getTableList()
  currentContract.value = { ...row }
  approvalType.value = type
  approvalForm.comment = ''
  approvalDialogVisible.value = true
}

// 审核相关状态
const approvalDialogVisible = ref(false)
const approvalLoading = ref(false)
const currentContract = ref<any>({})
const approvalType = ref<number>(0) // 0-通过，1-不通过

const approvalForm = reactive({
  comment: ''
})

// 计算属性
const approvalTitle = computed(() => {
  return approvalType.value === 0 ? '合同审核通过' : '合同审核不通过'
})

const approvalPlaceholder = computed(() => {
  return approvalType.value === 0 ? '请输入审核通过的意见...' : '请输入审核不通过的原因...'
})
// 关闭对话框
const handleDialogClose = () => {
  approvalDialogVisible.value = false
  approvalForm.comment = ''
}

// 提交审核
const submitApproval = async () => {
  if (!approvalForm.comment.trim()) {
    ElMessage.warning('请输入审核意见')
    return
  }

  approvalLoading.value = true
  try {
    const params = {
      id: currentContract.value.id,
      type: approvalType.value,
      comment: approvalForm.comment.trim()
    }

    await useHandleData(ContractApi.approvalContract, params, approvalType.value === 0 ? '合同审核通过' : '合同审核不通过')

    approvalDialogVisible.value = false
    proTable.value.getTableList()
  } catch (error) {
    console.error('审核提交失败:', error)
  } finally {
    approvalLoading.value = false
  }
}
</script>
